from pathlib import Path
from typing import Literal, Optional

from pydantic import BaseModel
from pydantic_settings import BaseSettings
import yaml
import os
from dotenv import load_dotenv


class ServerConfig(BaseModel):
    port: int
    host: str
    reload: bool = False

class MongoConfig(BaseModel):
    host: str
    port: int
    username: str
    password: str
    database: str
    pool_size: int = 10  # 连接池大小

class RedisConfig(BaseSettings):
    """Redis配置类"""
    host: str
    port: int
    password: Optional[str] = None
    db: int = 0
    pool_size: int = 10  # 连接池大小

class MySQLConfig(BaseModel):
    """MySQL配置类"""
    host: str = "localhost"
    port: int = 3306
    user: str = "core_select"
    password: str = "core_select"
    database: str = "core_select"
    pool_size: int = 20  # 连接池大小


class LoggingConfig(BaseModel):
    level: str = "INFO"
    rotation: str = "10 MB"  # 日志文件轮转大小
    retention: str = "7 days"  # 日志保留时间
    path: Optional[str] = None  # 日志文件路径，None表示不写入文件


class CoreSettings(BaseSettings):
    env: str = "dev"
    server: ServerConfig
    logging: LoggingConfig
    redis: RedisConfig
    mysql: MySQLConfig
    mongodb: MongoConfig

    @classmethod
    def load_config(cls):
        """加载YAML配置文件"""
        env = os.getenv('ENV', 'dev')
        config_file = Path(f"./app/configs/{env}.yaml")

        if not config_file.exists():
            raise FileNotFoundError(f"Config file {config_file} not found")

        with open(config_file, 'r', encoding='utf-8') as f:
            config_data = yaml.safe_load(f) or {}
            return cls(**config_data)

    class Config:
        env_file = ".env"
        env_file_encoding = 'utf-8'


_settings_instance = None

def get_settings() -> CoreSettings:
    """获取配置实例"""
    global _settings_instance
    if _settings_instance is None:
        load_dotenv()
        _settings_instance = CoreSettings.load_config()
    return _settings_instance
